package com.qiangesoft.im.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 根据名字创建头像
 *
 * @author qiangesoft
 * @date 2023-08-24
 */
public class AvatarPictureUtil {

    /**
     * 绘制字体头像
     *
     * @param name
     * @param atFirst
     * @param num
     * @throws IOException
     */
    public static BufferedImage generateImg(String name, boolean atFirst, int num) throws IOException {
        // 截取名字
        String nameStr = substringStr(name, atFirst, num);

        int width = 100;
        int height = 100;

        // 图片
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(getRandomColor());
        g2.clearRect(0, 0, width, height);
        g2.setPaint(Color.WHITE);

        // 两个字及以上
        if (nameStr.length() >= 2) {
            g2.setFont(new Font("微软雅黑", Font.PLAIN, 30));

            String firstWritten = nameStr.substring(0, 1);
            String secondWritten = nameStr.substring(1, 2);
            if (isChinese(firstWritten) && isChinese(secondWritten)) {
                g2.drawString(nameStr, 20, 60);
            } else if (isChinese(firstWritten) && !isChinese(secondWritten)) {
                g2.drawString(nameStr, 27, 60);
            } else if (!isChinese(firstWritten) && isChinese(secondWritten)) {
                g2.drawString(nameStr, 27, 60);
            } else {
                g2.drawString(nameStr, 30, 62);
            }
        }
        // 一个字
        if (nameStr.length() == 1) {
            if (isChinese(nameStr)) {
                g2.setFont(new Font("微软雅黑", Font.PLAIN, 50));
                g2.drawString(nameStr, 25, 70);
            } else {
                g2.setFont(new Font("微软雅黑", Font.PLAIN, 55));
                g2.drawString(nameStr.toUpperCase(), 31, 67);
            }
        }

        return makeRoundedCorner(bi, 99);
    }

    /**
     * 保存到本地
     *
     * @param name
     * @param outputPath
     * @throws IOException
     */
    public static void generateImg(String name, boolean atFirst, int num, String outputPath) throws IOException {
        Assert.isTrue(StringUtils.isNotBlank(outputPath), "文件输出路径不能为空");

        BufferedImage bufferedImage = generateImg(name, atFirst, num);

        String filename = outputPath + File.separator + UUID.randomUUID().toString().replace("-", "") + ".png";
        File file = new File(filename);
        ImageIO.write(bufferedImage, "png", file);
    }

    /**
     * 截取名字
     *
     * @param name
     * @param atFirst
     * @param num
     * @return
     */
    private static String substringStr(String name, boolean atFirst, int num) {
        Assert.isTrue(StringUtils.isNotBlank(name), "名字不能为空");
        Assert.isTrue(num < 3, "截取位数不能大于2");
        Assert.isTrue(num > 0, "截取位数不能小于1");

        int length = name.length();
        String nameStr;
        if (length <= num) {
            nameStr = name;
        } else {
            if (atFirst) {
                // 取前几位
                nameStr = name.substring(0, num).toUpperCase();
            } else {
                // 取后几位
                nameStr = name.substring(length - num).toUpperCase();
            }
        }
        return nameStr;
    }

    /**
     * 判断字符串是否为中文
     *
     * @param str
     * @return
     */
    private static boolean isChinese(String str) {
        String regEx = "[\\u4e00-\\u9fa5]+";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 获得随机颜色
     *
     * @return
     */
    private static Color getRandomColor() {
        String[] beautifulColors = new String[]{"232,221,203", "205,179,128", "3,101,100", "3,54,73", "3,22,52",
                "237,222,139", "251,178,23", "96,143,159", "1,77,103", "254,67,101", "252,157,154",
                "249,205,173", "200,200,169", "131,175,155", "229,187,129", "161,23,21", "34,8,7",
                "118,77,57", "17,63,61", "60,79,57", "95,92,51", "179,214,110", "248,147,29",
                "227,160,93", "178,190,126", "114,111,238", "56,13,49", "89,61,67", "250,218,141",
                "3,38,58", "179,168,150", "222,125,44", "20,68,106", "130,57,53", "137,190,178",
                "201,186,131", "222,211,140", "222,156,83", "23,44,60", "39,72,98", "153,80,84",
                "217,104,49", "230,179,61", "174,221,129", "107,194,53", "6,128,67", "38,157,128",
                "178,200,187", "69,137,148", "117,121,71", "114,83,52", "87,105,60", "82,75,46",
                "171,92,37", "100,107,48", "98,65,24", "54,37,17", "137,157,192", "250,227,113",
                "29,131,8", "220,87,18", "29,191,151", "35,235,185", "213,26,33", "160,191,124",
                "101,147,74", "64,116,52", "255,150,128", "255,94,72", "38,188,213", "167,220,224",
                "1,165,175", "179,214,110", "248,147,29", "230,155,3", "209,73,78", "62,188,202",
                "224,160,158", "161,47,47", "0,90,171", "107,194,53", "174,221,129", "6,128,67",
                "38,157,128", "201,138,131", "220,162,151", "137,157,192", "175,215,237", "92,167,186",
                "255,66,93", "147,224,255", "247,68,97", "185,227,217"};
        int len = beautifulColors.length;
        Random random = new Random();
        String[] color = beautifulColors[random.nextInt(len)].split(",");
        return new Color(Integer.parseInt(color[0]), Integer.parseInt(color[1]), Integer.parseInt(color[2]));
    }


    /**
     * 图片做圆角处理
     *
     * @param image
     * @param cornerRadius
     * @return
     */
    private static BufferedImage makeRoundedCorner(BufferedImage image, int cornerRadius) {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage output = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = output.createGraphics();
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, width, height, cornerRadius, cornerRadius));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        return output;
    }

    /**
     * @throws IOException
     * @throws
     **/
    public static void main(String[] args) throws IOException {
        generateImg("张三", false, 1, "D:\\");
        generateImg("adwda", false, 1, "D:\\");
        generateImg("张大胆", false, 2, "D:\\");
        generateImg("张s胆", false, 2, "D:\\");
        generateImg("s喀喀喀s", false, 2, "D:\\");
        generateImg("lixiaohe", false, 2, "D:\\");
    }
}